package com.cosmoplat.gfqd.utils;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class ClearDirectory {

    // 清空指定目录的方法
    public static void clear(String clearDirectory) {
        try {
            Path path = Paths.get(clearDirectory);
            if (Files.exists(path) && Files.isDirectory(path)) {
                Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        // 解除文件的只读属性
                        file.toFile().setWritable(true);
                        Files.deleteIfExists(file); // 尝试删除文件
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.deleteIfExists(dir); // 删除目录
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
            Files.createDirectories(path);
            System.out.println("Created path: " + clearDirectory);

        } catch (IOException e) {
            System.err.println("Failed to create directory: " + clearDirectory + " - " + e.getMessage());
        }
    }
}